// 报告页面模块
(function(SEDFramework) {
    'use strict';

    const ReportPageModule = {
        name: 'ReportPage',
        version: '1.0.0',

        // 模块配置
        config: {
            buttonContainer: '.report-header',
            buttons: [
                {
                    id: 'export-report',
                    text: '导出报告',
                    className: 'sed-btn sed-btn-success',
                    title: '导出当前报告为PDF',
                    handler: 'handleExportReport'
                },
                {
                    id: 'share-report',
                    text: '分享报告',
                    className: 'sed-btn sed-btn-primary',
                    title: '生成报告分享链接',
                    handler: 'handleShareReport'
                },
                {
                    id: 'debug-panel',
                    text: '接口监听',
                    className: 'sed-btn sed-btn-info',
                    title: '查看接口调用数据',
                    handler: 'handleDebugPanel'
                }
            ]
        },

        // 初始化模块
        init() {
            SEDFramework.log('报告页面模块初始化', 'info', this.name);
            
            // 检查是否在报告页面
            if (!SEDFramework.pageDetector.isReportPage()) {
                SEDFramework.log('不在报告页面，模块不执行', 'warn', this.name);
                return;
            }

            // 设置DOM观察器
            this.setupObserver();
            
            // 设置路由监听
            this.setupRouteListener();
            
            // 尝试立即添加按钮
            this.tryAddButtons();
        },

        // 设置DOM观察器
        setupObserver() {
            SEDFramework.observer.setup(() => {
                this.tryAddButtons();
            }, this.config.buttonContainer);
        },

        // 设置路由监听
        setupRouteListener() {
            SEDFramework.router.setup(() => {
                if (SEDFramework.pageDetector.isReportPage()) {
                    this.tryAddButtons();
                }
            });
        },

        // 尝试添加按钮
        tryAddButtons() {
            const container = document.querySelector(this.config.buttonContainer);
            if (container && !container.querySelector('.sed-btn')) {
                this.addButtons(container);
            }
        },

        // 添加按钮
        addButtons(container) {
            this.config.buttons.forEach(buttonConfig => {
                const button = this.createButton(buttonConfig);
                container.appendChild(button);
            });
            
            SEDFramework.log('报告页面按钮已添加', 'success', this.name);
        },

        // 创建按钮
        createButton(config) {
            const button = document.createElement('button');
            button.id = config.id;
            button.className = config.className;
            button.textContent = config.text;
            button.title = config.title;
            
            button.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this[config.handler](e);
            });
            
            return button;
        },

        // 处理导出报告
        handleExportReport(e) {
            SEDFramework.log('开始导出报告', 'info', this.name);
            
            const button = document.querySelector('#export-report');
            if (button) {
                button.disabled = true;
                button.textContent = '导出中...';
            }

            // 获取报告参数
            const reportParams = this.getReportParams();
            
            // 调用导出API
            this.callExportAPI(reportParams, () => {
                if (button) {
                    button.disabled = false;
                    button.textContent = '导出报告';
                }
            });
        },

        // 处理分享报告
        handleShareReport(e) {
            SEDFramework.log('开始生成分享链接', 'info', this.name);
            
            const button = document.querySelector('#share-report');
            if (button) {
                button.disabled = true;
                button.textContent = '生成中...';
            }

            // 获取报告参数
            const reportParams = this.getReportParams();
            
            // 调用分享API
            this.callShareAPI(reportParams, (shareUrl) => {
                if (button) {
                    button.disabled = false;
                    button.textContent = '分享报告';
                }
                
                if (shareUrl) {
                    this.showShareDialog(shareUrl);
                }
            });
        },

        // 处理调试面板
        handleDebugPanel(e) {
            if (window.APIMonitorLib) {
                const panel = document.getElementById('api-monitor-panel');
                if (panel) {
                    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
                } else {
                    window.APIMonitorLib.createDebugPanel({
                        title: 'SED接口监控',
                        position: 'top-right'
                    });
                }
            } else {
                alert('API监控库未加载');
            }
        },

        // 获取报告参数
        getReportParams() {
            const params = {};
            
            if (window.GlobalVarsManager) {
                const allVars = window.GlobalVarsManager.getAll();
                const relevantKeys = ['factory_no', 'factory_name', 'sub_factory_no', 'sub_factory_name', 
                                    'user_token', 'current_project', 'month_str', 'report_id'];
                
                for (const key of relevantKeys) {
                    if (allVars[key] && allVars[key].trim() !== '') {
                        params[key] = allVars[key];
                    }
                }
            }
            
            // 从URL获取额外参数
            const urlParams = new URLSearchParams(window.location.search);
            for (const [key, value] of urlParams.entries()) {
                if (value && value.trim() !== '') {
                    params[key] = value;
                }
            }
            
            return params;
        },

        // 调用导出API
        callExportAPI(params, callback) {
            const baseUrl = window.location.origin;
            const apiUrl = `${baseUrl}/external-api/report/export`;

            SEDFramework.log(`导出API请求参数: ${JSON.stringify(params)}`, 'info', this.name);

            GM_xmlhttpRequest({
                method: 'POST',
                url: apiUrl,
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                data: JSON.stringify(params),
                onload: (response) => {
                    callback();
                    
                    if (response.status === 200) {
                        try {
                            const result = JSON.parse(response.responseText);
                            if (result.success) {
                                SEDFramework.log('报告导出成功', 'success', this.name);
                                alert('报告导出成功！');
                            } else {
                                SEDFramework.log(`导出失败: ${result.message || '未知错误'}`, 'error', this.name);
                                alert('导出失败：' + (result.message || '未知错误'));
                            }
                        } catch (e) {
                            SEDFramework.log(`响应解析失败: ${e.message}`, 'error', this.name);
                            alert('响应解析失败：' + e.message);
                        }
                    } else {
                        SEDFramework.log(`请求失败，状态码: ${response.status}`, 'error', this.name);
                        alert('请求失败，状态码：' + response.status);
                    }
                },
                onerror: (error) => {
                    callback();
                    SEDFramework.log(`网络请求失败: ${error.message}`, 'error', this.name);
                    alert('网络请求失败：' + error.message);
                }
            });
        },

        // 调用分享API
        callShareAPI(params, callback) {
            const baseUrl = window.location.origin;
            const apiUrl = `${baseUrl}/external-api/report/share`;

            SEDFramework.log(`分享API请求参数: ${JSON.stringify(params)}`, 'info', this.name);

            GM_xmlhttpRequest({
                method: 'POST',
                url: apiUrl,
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                data: JSON.stringify(params),
                onload: (response) => {
                    if (response.status === 200) {
                        try {
                            const result = JSON.parse(response.responseText);
                            if (result.success && result.data && result.data.shareUrl) {
                                SEDFramework.log('分享链接生成成功', 'success', this.name);
                                callback(result.data.shareUrl);
                            } else {
                                SEDFramework.log(`分享失败: ${result.message || '未知错误'}`, 'error', this.name);
                                alert('分享失败：' + (result.message || '未知错误'));
                                callback(null);
                            }
                        } catch (e) {
                            SEDFramework.log(`响应解析失败: ${e.message}`, 'error', this.name);
                            alert('响应解析失败：' + e.message);
                            callback(null);
                        }
                    } else {
                        SEDFramework.log(`请求失败，状态码: ${response.status}`, 'error', this.name);
                        alert('请求失败，状态码：' + response.status);
                        callback(null);
                    }
                },
                onerror: (error) => {
                    SEDFramework.log(`网络请求失败: ${error.message}`, 'error', this.name);
                    alert('网络请求失败：' + error.message);
                    callback(null);
                }
            });
        },

        // 显示分享对话框
        showShareDialog(shareUrl) {
            const dialog = document.createElement('div');
            dialog.id = 'share-dialog';
            dialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border: 2px solid #3742fa;
                border-radius: 8px;
                padding: 20px;
                z-index: 10001;
                max-width: 500px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                font-family: Arial, sans-serif;
            `;
            
            dialog.innerHTML = `
                <h3 style="margin: 0 0 15px 0; color: #3742fa; text-align: center;">分享链接</h3>
                <div style="margin-bottom: 15px;">
                    <p style="margin: 0 0 10px 0; color: #2f3542;">报告分享链接已生成：</p>
                    <div style="background: #f8f9fa; padding: 10px; border-radius: 4px; word-break: break-all;">
                        <input type="text" value="${shareUrl}" readonly style="width: 100%; border: none; background: transparent; font-size: 12px;">
                    </div>
                </div>
                <div style="text-align: center;">
                    <button id="copy-link-btn" style="background: #3742fa; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; margin-right: 10px;">复制链接</button>
                    <button id="close-share-btn" style="background: #747d8c; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">关闭</button>
                </div>
            `;
            
            document.body.appendChild(dialog);
            
            // 绑定事件
            document.getElementById('copy-link-btn').addEventListener('click', function() {
                navigator.clipboard.writeText(shareUrl).then(() => {
                    alert('链接已复制到剪贴板！');
                }).catch(() => {
                    // 备用复制方法
                    const input = dialog.querySelector('input');
                    input.select();
                    document.execCommand('copy');
                    alert('链接已复制到剪贴板！');
                });
            });
            
            document.getElementById('close-share-btn').addEventListener('click', function() {
                dialog.remove();
            });
            
            // 点击背景关闭
            dialog.addEventListener('click', function(e) {
                if (e.target === dialog) {
                    dialog.remove();
                }
            });
        }
    };

    // 注册模块
    SEDFramework.moduleManager.register('ReportPage', ReportPageModule);
    
    // 自动初始化
    if (SEDFramework.pageDetector.isReportPage()) {
        ReportPageModule.init();
    }

    return ReportPageModule;
})(window.SEDFramework); 